package com.edu.dk.security.impl;

import java.util.Enumeration;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.edu.dk.security.WebContext;

/**
 * 
 * 功能说明: 实现了<code>WebContext</code>接口，包含request、response和servletContext的信息。
 */
public class SimpleWebContext extends CommitMonitor implements WebContext {

	private static final long serialVersionUID = 453271745634262835L;

	/**
	 * 创建一个新的<code>RequestContext</code>对象。
	 * 
	 * @param webContext
	 *            当前请求所在的<code>ServletContext</code>
	 * @param request
	 *            <code>HttpServletRequest</code>对象
	 * @param response
	 *            <code>HttpServletResponse</code>对象
	 */
	public SimpleWebContext(WebContext webContext, FilterHandler handler, HttpServletRequest request,
			HttpServletResponse response) {
		super(webContext, handler);
		setRequest(new RequestWrapper(request));
		setResponse(new CommittingAwareResponse(response, this));
	}

	/** 开始一个请求。 */
	public void prepare() {
	}

	/** 结束一个请求。 */
	public void commit() {
	}

	private class RequestWrapper extends AbstractRequestWrapper {

		public RequestWrapper(HttpServletRequest request) {
			super(SimpleWebContext.this, request);
		}

		@Override
		public Object getAttribute(String name) {
			Object object = super.getAttribute(name);
			if (object == null) {
				WebContext topWebContext = getTopWebContext();
				if (topWebContext != null) {
					object = getFromWrapperContext(name, getTopWebContext());
				}
			}
			return object;
		}

		@Override
		public Enumeration getAttributeNames() {
			return super.getAttributeNames();
		}

		@Override
		public void setAttribute(String name, Object value) {
			super.setAttribute(name, value);
		}

		@Override
		public void removeAttribute(String name) {
			super.removeAttribute(name);
		}

		@Override
		public RequestDispatcher getRequestDispatcher(String path) {
			return super.getRequestDispatcher(path);
		}

	}

}
